#include <stdio.h>
#include <string.h>

/* "AB" -> 0xAB */
int char_to_byte(const char *str_char, unsigned char *str_byte) {
	unsigned char byte_high = 0x00;
	unsigned char byte_low = 0x00;
	byte_high = *str_char;
	byte_low = *(str_char + 1);

	if ((str_char == NULL) || (str_byte == NULL))
		return -1;

	/* byte High */
	if ((byte_high >= '0') && (byte_high <= '9')) {
		byte_high = byte_high - '0';
	} else if ((byte_high >= 'a') && (byte_high <= 'f')) {
		byte_high = byte_high - 'a' + 0x0a;
	} else if ((byte_high >= 'A') && (byte_high <= 'F')) {
		byte_high = byte_high - 'A' + 0x0a;
	} else {
		return -1;
	}

	/* byte Low */
	if ((byte_low >= '0') && (byte_low <= '9')) {
		byte_low = byte_low - '0';
	} else if ((byte_low >= 'a') && (byte_low <= 'f')) {
		byte_low = byte_low - 'a' + 0x0a;
	} else if ((byte_low >= 'A') && (byte_low <= 'F')) {
		byte_low = byte_low - 'A' + 0x0a;
	} else {
		return -1;
	}

	*str_byte = (byte_high << 4) + byte_low;
	return 0;
}

/* "ABCD..." -> [0xAB, 0xCD, ...] */
int hex_str_convert(const char *str_in, char *str_out) {
	int i = 0;
	unsigned char tmp = 0;
	size_t len = strlen(str_in);

	for (i = 0; i < len / 2; i++) {
		if (char_to_byte(&str_in[i * 2], &tmp) == 0x00)
			*(str_out + i) = tmp;
		else
			return -1;
	}
	return 0;
}

int main() {
	char str_out[64] = { 0 };
	char str2_out[64] = { 0 };
	char str3_out[64] = { 0 };
	char str4_out[64] = { 0 };
	const char *str_in = "3131372E37342E3133362E33343B"; //ftp ip
	const char *str2_in = "32313B";                      //ftp port
	const char *str3_in = "63766E6176693B";              //ftp user
	const char *str4_in = "3037323946344236344D4D48455430365639"; //ftp 文件名

	hex_str_convert(str_in, str_out);
	hex_str_convert(str2_in, str2_out);
	hex_str_convert(str3_in, str3_out);
	hex_str_convert(str4_in, str4_out);
	printf(str_out);
	printf("\n");
	printf(str2_out);
	printf("\n");
	printf(str3_out);
	printf("\n");
	printf(str4_out);
	
	return 0;
}
